package com.gexin.weixin.controller.demo;

import java.util.Map;
import com.gexin.weixin.controller.base.WxBaseController;
import com.gexin.weixin.kit.WeiXinUtils;
import com.jfinal.aop.Before;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.HttpKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.kit.PaymentKit;

@ControllerBind(controllerKey = "/weixin/pay/notify", viewPath = "WEB-INF/extend/weixin/")
public class WexinPayNotifyController extends WxBaseController {
	private static final Log log = Log.getLog(WexinPayNotifyController.class);
	@Before(Tx.class)
	public void index() {
		try {
			 String xmlMsg = HttpKit.readData(getRequest());
			 log.info("微信支付成功回调====="+xmlMsg);
	         Map<String, String> map = PaymentKit.xmlToMap(xmlMsg);
			if (map != null && map.get("result_code").toString().trim().equals("SUCCESS")) {
				// 如果验证码成功 要判断订单别重复提交了
				String out_trade_no = map.get("out_trade_no");// 支付订单ID
				String transaction_id = map.get("transaction_id");// 回调地址
				Integer total_fee = Integer.parseInt(map.get("total_fee"));// 支付多少钱
				log.info(String.format("订单支付成功通知，内部ID:%s,微信支付ID:%s,支付金额：%s分",out_trade_no, transaction_id,total_fee));
				boolean  is_ok = total_fee>0;
				if(is_ok){
					//处理成功
					renderText(WeiXinUtils.wxPayResponse("SUCCESS", ""));
				}else{
					renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
				}
			}
		}catch(Exception e){
			 e.printStackTrace();
			 log.error("支付回调发生异常错误:"+e.getMessage());
			 renderText(WeiXinUtils.wxPayResponse("FAIL", ""));
		}
	}
	
	/*
	 * 支付结果返回
	 * <xml><appid><![CDATA[wx85fd6dd575348b58]]></appid>
	<bank_type><![CDATA[CFT]]></bank_type>
	<cash_fee><![CDATA[1]]></cash_fee>
	<fee_type><![CDATA[CNY]]></fee_type>
	<is_subscribe><![CDATA[Y]]></is_subscribe>
	<mch_id><![CDATA[1233073302]]></mch_id>
	<nonce_str><![CDATA[1467010416]]></nonce_str>
	<openid><![CDATA[o4wIdsyQGhZw4wryeN25oOzlWK7k]]></openid>
	<out_trade_no><![CDATA[6421467010416608]]></out_trade_no>
	<result_code><![CDATA[SUCCESS]]></result_code>
	<return_code><![CDATA[SUCCESS]]></return_code>
	<sign><![CDATA[8E4075A00AAF7585AC09A7B7FA6DE680]]></sign>
	<time_end><![CDATA[20160627145435]]></time_end>
	<total_fee>1</total_fee>
	<trade_type><![CDATA[JSAPI]]></trade_type>
	<transaction_id><![CDATA[4001772001201606277968238239]]></transaction_id>
	</xml>*/
}
